package com.bigegg.employee.service.impl;

import com.bigegg.employee.domain.*;
import com.bigegg.employee.dto.*;
import com.bigegg.employee.util.DistanceUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 活动service
 * 单独封装的service 给小程序提供接口
 */
@Service
public class JobActivityService {

    @Autowired
    private ActivityServiceImpl activityService;

    @Autowired
    private ActivitySignServiceImpl activitySignService;

    @Autowired
    CUserService cUserService;


    /**
     * 查询正在举办的活动
     */
    public List<Activity> listHoldingActivity() {

        Activity activity = new Activity();
        activity.setStatus(1);
        return activityService.selectActivityList(activity);
    }

    @Autowired
    GraduateServiceImpl graduateService;

    /**
     * 获取 活动签到 统计
     */
    public ActSignSta getActivitySignStat(Long actId, LoginUser user) {

        TypeUserInfo info = cUserService.getUserInfo(user);
        if (info == null) {
            throw new ServiceException("无效的用户身份");
        }
        Activity activity = activityService.selectActivityById(actId);
        if (activity == null) {
            throw new ServiceException("无效的活动ID [" + actId + "]");
        }

        ActSignSta actSignSta = new ActSignSta();
        Long c;
        // 辅导员统计 自己班级的
        if (info instanceof TypeTeacherInfo) {
            List<Classes> classes = ((TypeTeacherInfo) info).getClasses();
            if (classes != null) {
                List<Long> classIdList = classes.stream().map(Classes::getId).collect(Collectors.toList());
                List<Graduate> graduateList = graduateService.getGraCntByClasses(classIdList);
                c = 0L;
                if (graduateList != null) {
                    for (Graduate g : graduateList) {
                        c += g.getCnt();
                    }
                }

                // 活动总签到人数
                int countSign = activitySignService.getCountClassSign(actId, classIdList);
                actSignSta.setActivitySigned(countSign);
                // 活动单位总签到人数
                int countUnitSign = activitySignCompService.getCountClassSign(actId, classIdList);
                actSignSta.setUnitSigned(countUnitSign);
            } else {
                return actSignSta;
            }
        } else {

            c = graduateService.getGraCnt(new Graduate()).getCnt();
            // 学校的统计所有的
            // 活动总签到人数
            int countSign = activitySignService.getCountSign(actId);
            actSignSta.setActivitySigned(countSign);
            // 活动单位总签到人数
            int countUnitSign = activitySignCompService.getCountSign(actId);
            actSignSta.setUnitSigned(countUnitSign);
        }

        actSignSta.setCount(Math.toIntExact(c));
        actSignSta.setActivityNotsigned((int) (c - actSignSta.getActivitySigned()));
        actSignSta.setUnitNotsigned((int) (c - actSignSta.getUnitSigned()));
        return actSignSta;
    }

    @Autowired
    private MajorServiceImpl majorService;

    /**
     * 查询学院下所有专业
     *
     * @param collegeId 学院ID
     * @return 专业
     */
    private List<Major> getMajorList(Long collegeId) {
        Major filter = new Major();
        filter.setCollegeId(collegeId);
        return majorService.selectMajorList(filter);
    }

    /**
     * 获取部门（学院） 活动签到 统计
     */
    public List<MajorActSignSta> getDepartmentActivitySignStat(Long actId, Long deptId, LoginUser user) {

        TypeUserInfo info = cUserService.getUserInfo(user);
        if (info == null) {
            throw new ServiceException("无效的用户身份");
        }
        Activity activity = activityService.selectActivityById(actId);
        if (activity == null) {
            throw new ServiceException("无效的活动ID [" + actId + "]");
        }
        // List<Major> majorList = getMajorList(deptId);
        Graduate graduate = new Graduate();
        graduate.setCollegeId(deptId);
        List<Graduate> graduates = graduateService.getGraCntByMajor(graduate);
        List<MajorActSignSta> majorActSignStaList = new ArrayList<>();
        if (graduates != null) {
            List<MajorActSignSta> actList = activitySignService.getCountMajorSign(actId, deptId);
            List<MajorActSignSta> unitList = activitySignCompService.getCountMajorSign(actId, deptId);
            for (Graduate g1 : graduates) {
                MajorActSignSta one = new MajorActSignSta();
                one.setCount(Math.toIntExact(g1.getCnt()));
                one.setId(g1.getMajorId());
                one.setName(g1.getMajorName());
                MajorActSignSta actSign = actList.stream().filter(a -> a.getId().equals(g1.getMajorId())).findFirst().orElse(null);
                if (actSign != null) {
                    one.setActivitySigned(actSign.getCount());
                    one.setActivityNotsigned(one.getCount() - one.getActivitySigned());
                }
                MajorActSignSta unitSign = unitList.stream().filter(a -> a.getId().equals(g1.getMajorId())).findFirst().orElse(null);
                if (unitSign != null) {
                    one.setUnitSigned(unitSign.getCount());
                    one.setUnitNotsigned(one.getCount() - one.getUnitSigned());
                }
                majorActSignStaList.add(one);
            }
        }

        return majorActSignStaList;
    }


    /**
     * 查询单位签到详情
     *
     * @param activityId 活动ID
     * @return UnitSignSta
     */
    public UnitSignSta getUnitActivitySignStat(Long activityId) {
        UnitSignSta unitSignSta = new UnitSignSta();
        int signed = activitySignService.getCountSign(activityId);
        unitSignSta.setSigned(signed);
        Long c = graduateService.getGraCnt(new Graduate()).getCnt();
        unitSignSta.setCount(Math.toIntExact(c));
        unitSignSta.setDetail(activitySignCompService.getUnitSignCount(activityId));
        return unitSignSta;

    }

    @Autowired
    private ActivitySignServiceImpl activitySignServiceImpl;

    @Autowired
    private ActivitySignCompServiceImpl activitySignCompService;


    /**
     * 单位签到
     *
     * @param actSignBody UnitActSignBody
     * @param user        用户
     */
    public void doUnitSign(UnitActSignBody actSignBody, LoginUser user) {
        TypeUserInfo info = cUserService.getUserInfo(user);
        if (!(info instanceof TypeStudentInfo)) {
            throw new ServiceException("无效的用户身份");
        }
        TypeStudentInfo studentInfo = (TypeStudentInfo) info;
        Long stuId = studentInfo.getStudentId();

        if (activitySignCompService.hasSigned(actSignBody.getActivity_id(), actSignBody.getUnit_id(), stuId)) {
            throw new ServiceException("已经签到过了");
        }
        judgeDistance(actSignBody);

        ActivitySignComp activitySign = new ActivitySignComp();
        activitySign.setCompanyId(actSignBody.getUnit_id());
        activitySign.setActivityId(actSignBody.getActivity_id());
        activitySign.setLatitude(actSignBody.getLatitude() + "");
        activitySign.setLongitude(actSignBody.getLongitude() + "");
        activitySign.setStuId(stuId);
        activitySign.setSiginTime(new Date());
        activitySign.setStuClass(studentInfo.getClassName());
        activitySign.setStuClassId(studentInfo.getClassId());
        activitySign.setStuMajor(studentInfo.getMajor());
        activitySign.setStuMajorId(studentInfo.getMajorId());
        activitySign.setStuCollege(studentInfo.getDepartment());
        activitySign.setStuCollegeId(studentInfo.getDepartmentId());
        activitySignCompService.insertActivitySignComp(activitySign);

    }

    // 判断距离
    private void judgeDistance(ActSignBody actSignBody) {
        Activity activity = activityService.selectActivityById(actSignBody.getActivity_id());
        if (activity.getLatitude() != null && activity.getLatitude() != null && activity.getSignRange() != null) {
            double distance = DistanceUtil.getDistance(Double.parseDouble(activity.getLongitude()), Double.parseDouble(activity.getLatitude()),
                    actSignBody.getLongitude().doubleValue(), actSignBody.getLatitude().doubleValue());
            if (distance > activity.getSignRange()) {
                throw new ServiceException("超出签到范围,请在距离会场" + activity.getSignRange() + "米内进行签到");
            }
        }
    }

    /**
     * 活动签到
     *
     * @param actSignBody UnitActSignBody
     * @param user        用户
     */
    public void doActivitySign(ActSignBody actSignBody, LoginUser user) {
        TypeUserInfo info = cUserService.getUserInfo(user);
        if (!(info instanceof TypeStudentInfo)) {
            throw new ServiceException("无效的用户身份");
        }
        TypeStudentInfo studentInfo = (TypeStudentInfo) info;
        Long stuId = studentInfo.getStudentId();

        if (activitySignService.hasSigned(actSignBody.getActivity_id(), stuId)) {
            throw new ServiceException("已经签到过了");
        }
        judgeDistance(actSignBody);
        ActivitySign activitySign = new ActivitySign();
        activitySign.setActivityId(actSignBody.getActivity_id());
        activitySign.setLatitude(actSignBody.getLatitude() + "");
        activitySign.setLongitude(actSignBody.getLongitude() + "");
        activitySign.setStuId(stuId);
        activitySign.setSiginTime(new Date());
        activitySign.setStuClass(studentInfo.getClassName());
        activitySign.setStuClassId(studentInfo.getClassId());
        activitySign.setStuMajor(studentInfo.getMajor());
        activitySign.setStuMajorId(studentInfo.getMajorId());
        activitySign.setStuCollege(studentInfo.getDepartment());
        activitySign.setStuCollegeId(studentInfo.getDepartmentId());
        activitySignServiceImpl.insertActivitySign(activitySign);

    }

    @Autowired
    private CompanyInfoServiceImpl companyInfoService;

    @Autowired
    private ActivityBoothServiceImpl activityBoothService;

    /**
     * 查询单位签到详情
     *
     * @param actSignBody UnitActSignBody
     * @param user        LoginUser
     * @return 单位签到详情
     */
    public SignUnitDetail getActUnitInfoDetail(UnitActSignBody actSignBody, LoginUser user) {

        ActivityBooth booth = new ActivityBooth();
        booth.setActivityId(actSignBody.getActivity_id());
        booth.setCompanyId(actSignBody.getUnit_id());
        List<ActivityBooth> booths = activityBoothService.selectActivityBoothList(booth);
        if (booths == null || booths.size() < 1) {
            throw new ServiceException("无效的展位");
        }
        TypeUserInfo stuInfo = cUserService.getUserInfo(user);
        if (!(stuInfo instanceof TypeStudentInfo)) {
            throw new ServiceException("无效的用户身份");
        }
        Long stuId = ((TypeStudentInfo) stuInfo).getStudentId();
        boolean hasSigned = activitySignCompService.hasSigned(actSignBody.getActivity_id(), actSignBody.getUnit_id(), stuId);
        ActivityBooth b0 = booths.get(0);
        CompanyInfo info = companyInfoService.selectCompanyInfoById(b0.getCompanyId());
        SignUnitDetail detail = new SignUnitDetail();
        detail.setName(info.getName());
        detail.setAddress(info.getLocation());
        detail.setClassification(info.getTrade());
        detail.setScale(info.getScale());
        detail.setType(info.getNature());
        detail.setCanSign(1);
        detail.setSignStatus(hasSigned ? 1 : 0);
        detail.setDetail(info.getDescription());
        detail.setBanner(b0.getPoster());
        return detail;
    }


    /**
     * 查询活动签到详情
     *
     * @param actSignBody UnitActSignBody
     * @param loginUser   LoginUser
     * @return 查询活动签到详情
     */
    public SignActDetail getActInfoDetail(ActSignBody actSignBody, LoginUser loginUser) {

        TypeUserInfo stuInfo = cUserService.getUserInfo(loginUser);
        if (!(stuInfo instanceof TypeStudentInfo)) {
            throw new ServiceException("无效的用户身份");
        }
        Long stuId = ((TypeStudentInfo) stuInfo).getStudentId();
        boolean hasSigned = activitySignService.hasSigned(actSignBody.getActivity_id(), stuId);
        Activity activity = activityService.selectActivityById(actSignBody.getActivity_id());
        SignActDetail detail = new SignActDetail();
        detail.setName(activity.getActivityName());
        detail.setType(activity.getActivityType());
        detail.setAddress(activity.getAddress());
        detail.setDate(activity.getHoldStartTime());
        detail.setDetail(activity.getDetail());
        detail.setCanSign(1);
        detail.setSignStatus(hasSigned ? 1 : 0);
        detail.setBanner(null);
        return detail;
    }

    @Autowired
    CollegeServiceImpl collegeService;


    /**
     * 查询部门列表
     *
     * @return 部门列表
     */
    public List<College> getDepartmentList() {
        return collegeService.selectCollegeList(new College());
    }

    /**
     * 查询活动签到详情
     *
     * @return 活动签到详情
     */
    public List<ActSignDetail> getActivitySignDetail() {
        Long c = graduateService.getGraCnt(new Graduate()).getCnt();
        List<ActSignDetail> list = activitySignServiceImpl.getActivitySignDetail();
        if (list != null) {
            for (ActSignDetail detail : list) {
                detail.setCount(Math.toIntExact(c));
                detail.setActivityNotsigned(detail.getCount() - detail.getActivitySigned());
                detail.setUnitNotsigned(detail.getCount() - detail.getUnitSigned());
            }
        }
        return list;
    }

    /**
     * 辅导员查询自己的班级
     *
     * @param loginUser 用户
     * @return 班级列表
     */
    public List<SimpleClass> getTeacherClasses(LoginUser loginUser) {
        TypeUserInfo info = cUserService.getUserInfo(loginUser);
        if (!(info instanceof TypeTeacherInfo)) {
            throw new ServiceException("无效的用户身份");
        }
        // 辅导员统计 自己班级的
        List<Classes> list = ((TypeTeacherInfo) info).getClasses();
        if (list == null) return new ArrayList<>();
        return list.stream().map(a -> new SimpleClass(a.getId(), a.getName())).collect(Collectors.toList());
    }

    /**
     * 辅导员查询班级学生统计详情
     *
     * @param actClass  班级
     * @param loginUser 用户
     * @return 统计详情
     */
    public List<StuSign> getClassDetail(ActClass actClass, LoginUser loginUser) {

        List<SimpleClass> classes = getTeacherClasses(loginUser);
        if (classes == null || classes.stream().noneMatch(a -> a.getId().equals(actClass.getClass_id())))
            return new ArrayList<>();
        return activitySignServiceImpl.getClassDetail(actClass.getActivity_id(), actClass.getClass_id());
    }

    /**
     * 辅导员查询班级统计详情
     *
     * @param actClass  班级
     * @param loginUser 用户
     * @return 统计详情
     */
    public ActSignSta getClassSignedData(ActClass actClass, LoginUser loginUser) {
        List<SimpleClass> classes = getTeacherClasses(loginUser);
        if (classes == null || classes.stream().noneMatch(a -> a.getId().equals(actClass.getClass_id())))
            return new ActSignSta();
        List<Long> classIdList = Collections.singletonList(actClass.getClass_id());
        List<Graduate> list = graduateService.getGraCntByClasses(classIdList);
        ActSignSta signSta = new ActSignSta();
        if (list != null && list.size() > 0) {
            Graduate one = list.get(0);
            int c = Math.toIntExact(one.getCnt());
            signSta.setCount(c);
            // 活动总签到人数
            int countSign = activitySignService.getCountClassSign(actClass.getActivity_id(), classIdList);
            signSta.setActivitySigned(countSign);
            // 活动单位总签到人数
            int countUnitSign = activitySignCompService.getCountClassSign(actClass.getActivity_id(), classIdList);
            signSta.setUnitSigned(countUnitSign);
            signSta.setActivityNotsigned(c - signSta.getActivitySigned());
            signSta.setUnitNotsigned(c - signSta.getUnitSigned());

        }
        return signSta;
    }
}
